Write a short description about the course and add a link to your GitHub repository here. This is an R Markdown (.Rmd) file so you can use R Markdown syntax. ‘I am feeling great’ ‘I heard of this course from University of Eastern Finland Pages’ ‘I expect to use R program and datascience tools for my research’
Here is the link to my Girhub repository: https://github.com/mohanbabu29/IODS-project
and Here is the link to the my [diary page]: (https://mohanbabu29.github.io/IODS-project/).
output: html_document: default pdf_document: default — # Regression and model validation
Describe the work you have done this week and summarize your learning.
This week we understood data wrangling, perform explanatory examination and fit a simple linear model to the data.
Let’s read the data
library(dplyr)
learning2014 <-readxl::read_excel("~/IODS-project/data 2/learning2014.xlsx") %>%
mutate_at(vars(gender), factor)
str(learning2014)
## Classes 'tbl_df', 'tbl' and 'data.frame': 166 obs. of 7 variables:
## $ gender : Factor w/ 2 levels "F","M": 1 2 1 2 2 1 2 1 2 1 ...
## $ age : num 53 55 49 53 49 38 50 37 37 42 ...
## $ attitude: num 3.7 3.1 2.5 3.5 3.7 3.8 3.5 2.9 3.8 2.1 ...
## $ deep : num 3.58 2.92 3.5 3.5 3.67 ...
## $ stra : num 3.38 2.75 3.62 3.12 3.62 ...
## $ surf : num 2.58 3.17 2.25 2.25 2.83 ...
## $ points : num 25 12 24 10 22 21 21 31 24 26 ...
library(ggplot2)
pairs(learning2014[!names(learning2014) %in% c("gender")],col=learning2014$gender)
summary(learning2014)
## gender age attitude deep stra
## F:110 Min. :17.00 Min. :1.400 Min. :1.583 Min. :1.250
## M: 56 1st Qu.:21.00 1st Qu.:2.600 1st Qu.:3.333 1st Qu.:2.625
## Median :22.00 Median :3.200 Median :3.667 Median :3.188
## Mean :25.51 Mean :3.143 Mean :3.680 Mean :3.121
## 3rd Qu.:27.00 3rd Qu.:3.700 3rd Qu.:4.083 3rd Qu.:3.625
## Max. :55.00 Max. :5.000 Max. :4.917 Max. :5.000
## surf points
## Min. :1.583 Min. : 7.00
## 1st Qu.:2.417 1st Qu.:19.00
## Median :2.833 Median :23.00
## Mean :2.787 Mean :22.72
## 3rd Qu.:3.167 3rd Qu.:27.75
## Max. :4.333 Max. :33.00
library(GGally)
library(ggplot2)
# create a more advanced plot matrix with ggpairs()
ggpairs(learning2014,
mapping = aes(col = gender, alpha = 0.3),
lower = list(combo = wrap("facethist", bins = 20))
)
qplot(attitude, points, data = learning2014) + geom_smooth(method = "lm")
my_model <- lm(points ~ attitude, data = learning2014)
results <- summary(my_model)
knitr::kable(results$coefficients, digits=3, caption="Regression coefficients")
| Estimate | Std. Error | t value | Pr(>|t|) | |
|---|---|---|---|---|
| (Intercept) | 11.637 | 1.830 | 6.358 | 0 |
| attitude | 3.525 | 0.567 | 6.214 | 0 |
plot(my_model, which=c(1,2,5))
Describe the work you have done this week and summarize your learning.
This week we understood data wrangling, perform explanatory examination and fit a simple linear model to the data.
Let’s read the data
library(dplyr)
learning2014 <-readxl::read_excel("~/IODS-project/data 2/learning2014.xlsx") %>%
mutate_at(vars(gender), factor)
str(learning2014)
## Classes 'tbl_df', 'tbl' and 'data.frame': 166 obs. of 7 variables:
## $ gender : Factor w/ 2 levels "F","M": 1 2 1 2 2 1 2 1 2 1 ...
## $ age : num 53 55 49 53 49 38 50 37 37 42 ...
## $ attitude: num 3.7 3.1 2.5 3.5 3.7 3.8 3.5 2.9 3.8 2.1 ...
## $ deep : num 3.58 2.92 3.5 3.5 3.67 ...
## $ stra : num 3.38 2.75 3.62 3.12 3.62 ...
## $ surf : num 2.58 3.17 2.25 2.25 2.83 ...
## $ points : num 25 12 24 10 22 21 21 31 24 26 ...
dim(learning2014)
## [1] 166 7
library(ggplot2)
pairs(learning2014[!names(learning2014) %in% c("gender")],col=learning2014$gender)
summary(learning2014)
## gender age attitude deep stra
## F:110 Min. :17.00 Min. :1.400 Min. :1.583 Min. :1.250
## M: 56 1st Qu.:21.00 1st Qu.:2.600 1st Qu.:3.333 1st Qu.:2.625
## Median :22.00 Median :3.200 Median :3.667 Median :3.188
## Mean :25.51 Mean :3.143 Mean :3.680 Mean :3.121
## 3rd Qu.:27.00 3rd Qu.:3.700 3rd Qu.:4.083 3rd Qu.:3.625
## Max. :55.00 Max. :5.000 Max. :4.917 Max. :5.000
## surf points
## Min. :1.583 Min. : 7.00
## 1st Qu.:2.417 1st Qu.:19.00
## Median :2.833 Median :23.00
## Mean :2.787 Mean :22.72
## 3rd Qu.:3.167 3rd Qu.:27.75
## Max. :4.333 Max. :33.00
library(GGally)
library(ggplot2)
# create a more advanced plot matrix with ggpairs()
ggpairs(learning2014,
mapping = aes(col = gender, alpha = 0.3),
lower = list(combo = wrap("facethist", bins = 20))
)
qplot(attitude, points, data = learning2014) + geom_smooth(method = "lm")
my_model <- lm(points ~ attitude, data = learning2014)
results <- summary(my_model)
knitr::kable(results$coefficients, digits=3, caption="Regression coefficients")
| Estimate | Std. Error | t value | Pr(>|t|) | |
|---|---|---|---|---|
| (Intercept) | 11.637 | 1.830 | 6.358 | 0 |
| attitude | 3.525 | 0.567 | 6.214 | 0 |
plot(my_model, which=c(1,2,5))
>>>>>>> c98635c5e8506d39b39832ad4d622771b7ae5bed “C:/Program Files/Git/bin/git” config –mohanbabu29 ***
Let’s read the data
library(dplyr)
alc<- read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/alc.txt", sep=",", header=TRUE)
print<-vars(alc)
str(alc)
## 'data.frame': 382 obs. of 35 variables:
## $ school : Factor w/ 2 levels "GP","MS": 1 1 1 1 1 1 1 1 1 1 ...
## $ sex : Factor w/ 2 levels "F","M": 1 1 1 1 1 2 2 1 2 2 ...
## $ age : int 18 17 15 15 16 16 16 17 15 15 ...
## $ address : Factor w/ 2 levels "R","U": 2 2 2 2 2 2 2 2 2 2 ...
## $ famsize : Factor w/ 2 levels "GT3","LE3": 1 1 2 1 1 2 2 1 2 1 ...
## $ Pstatus : Factor w/ 2 levels "A","T": 1 2 2 2 2 2 2 1 1 2 ...
## $ Medu : int 4 1 1 4 3 4 2 4 3 3 ...
## $ Fedu : int 4 1 1 2 3 3 2 4 2 4 ...
## $ Mjob : Factor w/ 5 levels "at_home","health",..: 1 1 1 2 3 4 3 3 4 3 ...
## $ Fjob : Factor w/ 5 levels "at_home","health",..: 5 3 3 4 3 3 3 5 3 3 ...
## $ reason : Factor w/ 4 levels "course","home",..: 1 1 3 2 2 4 2 2 2 2 ...
## $ nursery : Factor w/ 2 levels "no","yes": 2 1 2 2 2 2 2 2 2 2 ...
## $ internet : Factor w/ 2 levels "no","yes": 1 2 2 2 1 2 2 1 2 2 ...
## $ guardian : Factor w/ 3 levels "father","mother",..: 2 1 2 2 1 2 2 2 2 2 ...
## $ traveltime: int 2 1 1 1 1 1 1 2 1 1 ...
## $ studytime : int 2 2 2 3 2 2 2 2 2 2 ...
## $ failures : int 0 0 3 0 0 0 0 0 0 0 ...
## $ schoolsup : Factor w/ 2 levels "no","yes": 2 1 2 1 1 1 1 2 1 1 ...
## $ famsup : Factor w/ 2 levels "no","yes": 1 2 1 2 2 2 1 2 2 2 ...
## $ paid : Factor w/ 2 levels "no","yes": 1 1 2 2 2 2 1 1 2 2 ...
## $ activities: Factor w/ 2 levels "no","yes": 1 1 1 2 1 2 1 1 1 2 ...
## $ higher : Factor w/ 2 levels "no","yes": 2 2 2 2 2 2 2 2 2 2 ...
## $ romantic : Factor w/ 2 levels "no","yes": 1 1 1 2 1 1 1 1 1 1 ...
## $ famrel : int 4 5 4 3 4 5 4 4 4 5 ...
## $ freetime : int 3 3 3 2 3 4 4 1 2 5 ...
## $ goout : int 4 3 2 2 2 2 4 4 2 1 ...
## $ Dalc : int 1 1 2 1 1 1 1 1 1 1 ...
## $ Walc : int 1 1 3 1 2 2 1 1 1 1 ...
## $ health : int 3 3 3 5 5 5 3 1 1 5 ...
## $ absences : int 6 4 10 2 4 10 0 6 0 0 ...
## $ G1 : int 5 5 7 15 6 15 12 6 16 14 ...
## $ G2 : int 6 5 8 14 10 15 12 5 18 15 ...
## $ G3 : int 6 6 10 15 10 15 11 6 19 15 ...
## $ alc_use : num 1 1 2.5 1 1.5 1.5 1 1 1 1 ...
## $ high_use : logi FALSE FALSE TRUE FALSE FALSE FALSE ...
alc <- mutate(alc, high_use = alc_use > 2)
glimpse(alc)
## Observations: 382
## Variables: 35
## $ school <fct> GP, GP, GP, GP, GP, GP, GP, GP, GP, GP, GP, GP, GP,...
## $ sex <fct> F, F, F, F, F, M, M, F, M, M, F, F, M, M, M, F, F, ...
## $ age <int> 18, 17, 15, 15, 16, 16, 16, 17, 15, 15, 15, 15, 15,...
## $ address <fct> U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, ...
## $ famsize <fct> GT3, GT3, LE3, GT3, GT3, LE3, LE3, GT3, LE3, GT3, G...
## $ Pstatus <fct> A, T, T, T, T, T, T, A, A, T, T, T, T, T, A, T, T, ...
## $ Medu <int> 4, 1, 1, 4, 3, 4, 2, 4, 3, 3, 4, 2, 4, 4, 2, 4, 4, ...
## $ Fedu <int> 4, 1, 1, 2, 3, 3, 2, 4, 2, 4, 4, 1, 4, 3, 2, 4, 4, ...
## $ Mjob <fct> at_home, at_home, at_home, health, other, services,...
## $ Fjob <fct> teacher, other, other, services, other, other, othe...
## $ reason <fct> course, course, other, home, home, reputation, home...
## $ nursery <fct> yes, no, yes, yes, yes, yes, yes, yes, yes, yes, ye...
## $ internet <fct> no, yes, yes, yes, no, yes, yes, no, yes, yes, yes,...
## $ guardian <fct> mother, father, mother, mother, father, mother, mot...
## $ traveltime <int> 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 3, 1, 2, 1, 1, 1, ...
## $ studytime <int> 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 3, 1, 2, 3, 1, 3, ...
## $ failures <int> 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...
## $ schoolsup <fct> yes, no, yes, no, no, no, no, yes, no, no, no, no, ...
## $ famsup <fct> no, yes, no, yes, yes, yes, no, yes, yes, yes, yes,...
## $ paid <fct> no, no, yes, yes, yes, yes, no, no, yes, yes, yes, ...
## $ activities <fct> no, no, no, yes, no, yes, no, no, no, yes, no, yes,...
## $ higher <fct> yes, yes, yes, yes, yes, yes, yes, yes, yes, yes, y...
## $ romantic <fct> no, no, no, yes, no, no, no, no, no, no, no, no, no...
## $ famrel <int> 4, 5, 4, 3, 4, 5, 4, 4, 4, 5, 3, 5, 4, 5, 4, 4, 3, ...
## $ freetime <int> 3, 3, 3, 2, 3, 4, 4, 1, 2, 5, 3, 2, 3, 4, 5, 4, 2, ...
## $ goout <int> 4, 3, 2, 2, 2, 2, 4, 4, 2, 1, 3, 2, 3, 3, 2, 4, 3, ...
## $ Dalc <int> 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...
## $ Walc <int> 1, 1, 3, 1, 2, 2, 1, 1, 1, 1, 2, 1, 3, 2, 1, 2, 2, ...
## $ health <int> 3, 3, 3, 5, 5, 5, 3, 1, 1, 5, 2, 4, 5, 3, 3, 2, 2, ...
## $ absences <int> 6, 4, 10, 2, 4, 10, 0, 6, 0, 0, 0, 4, 2, 2, 0, 4, 6...
## $ G1 <int> 5, 5, 7, 15, 6, 15, 12, 6, 16, 14, 10, 10, 14, 10, ...
## $ G2 <int> 6, 5, 8, 14, 10, 15, 12, 5, 18, 15, 8, 12, 14, 10, ...
## $ G3 <int> 6, 6, 10, 15, 10, 15, 11, 6, 19, 15, 9, 12, 14, 11,...
## $ alc_use <dbl> 1.0, 1.0, 2.5, 1.0, 1.5, 1.5, 1.0, 1.0, 1.0, 1.0, 1...
## $ high_use <lgl> FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FAL...
alc %>% group_by(alc_use,age) %>% summarise(count = n())
## # A tibble: 41 x 3
## # Groups: alc_use [9]
## alc_use age count
## <dbl> <int> <int>
## 1 1 15 46
## 2 1 16 41
## 3 1 17 26
## 4 1 18 27
## 5 1 19 3
## 6 1 20 1
## 7 1.5 15 9
## 8 1.5 16 24
## 9 1.5 17 20
## 10 1.5 18 12
## # ... with 31 more rows
alc %>% group_by(alc_use,sex) %>% summarise(count = n())
## # A tibble: 17 x 3
## # Groups: alc_use [9]
## alc_use sex count
## <dbl> <fct> <int>
## 1 1 F 89
## 2 1 M 55
## 3 1.5 F 41
## 4 1.5 M 27
## 5 2 F 27
## 6 2 M 31
## 7 2.5 F 25
## 8 2.5 M 17
## 9 3 F 11
## 10 3 M 21
## 11 3.5 F 3
## 12 3.5 M 14
## 13 4 F 1
## 14 4 M 8
## 15 4.5 M 3
## 16 5 F 1
## 17 5 M 8
alc %>% group_by(alc_use,Medu) %>% summarise(count = n())
## # A tibble: 37 x 3
## # Groups: alc_use [9]
## alc_use Medu count
## <dbl> <int> <int>
## 1 1 0 1
## 2 1 1 18
## 3 1 2 41
## 4 1 3 33
## 5 1 4 51
## 6 1.5 1 10
## 7 1.5 2 22
## 8 1.5 3 12
## 9 1.5 4 24
## 10 2 1 5
## # ... with 27 more rows
alc %>% group_by(alc_use,Fedu) %>% summarise(count = n())
## # A tibble: 35 x 3
## # Groups: alc_use [9]
## alc_use Fedu count
## <dbl> <int> <int>
## 1 1 0 2
## 2 1 1 28
## 3 1 2 42
## 4 1 3 38
## 5 1 4 34
## 6 1.5 1 16
## 7 1.5 2 15
## 8 1.5 3 19
## 9 1.5 4 18
## 10 2 1 9
## # ... with 25 more rows
alc %>% group_by(alc_use,age) %>% boxplot
m <- glm(high_use ~ failures + absences + sex, data = alc, family = "binomial")
summary(m)
##
## Call:
## glm(formula = high_use ~ failures + absences + sex, family = "binomial",
## data = alc)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -2.6629 -0.8545 -0.5894 1.0339 2.0428
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -1.95397 0.22819 -8.563 < 2e-16 ***
## failures 0.40462 0.15024 2.693 0.00708 **
## absences 0.07294 0.01796 4.061 4.88e-05 ***
## sexM 0.98848 0.24453 4.042 5.29e-05 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 462.21 on 381 degrees of freedom
## Residual deviance: 418.64 on 378 degrees of freedom
## AIC: 426.64
##
## Number of Fisher Scoring iterations: 4
coef(m)
## (Intercept) failures absences sexM
## -1.95396790 0.40461608 0.07293654 0.98847614
OR <- coef(m) %>% exp
CI <- confint(m) %>% exp
## Waiting for profiling to be done...
cbind(OR, CI)
## OR 2.5 % 97.5 %
## (Intercept) 0.1417107 0.08883883 0.2178283
## failures 1.4987270 1.11549818 2.0187171
## absences 1.0756623 1.04072883 1.1163576
## sexM 2.6871365 1.67434331 4.3755694
probabilities <- predict(m, type = "response")
alc <- mutate(alc, probability = probabilities)
alc <- mutate(alc, prediction = probability > 0.5)
select(alc, failures, absences, sex, high_use, probability, prediction) %>% tail(10)
## failures absences sex high_use probability prediction
## 373 1 0 M FALSE 0.3633449 FALSE
## 374 1 14 M TRUE 0.6130701 TRUE
## 375 0 2 F FALSE 0.1408685 FALSE
## 376 0 7 F FALSE 0.1910175 FALSE
## 377 1 0 F FALSE 0.1751799 FALSE
## 378 0 0 F FALSE 0.1241213 FALSE
## 379 1 0 F FALSE 0.1751799 FALSE
## 380 1 0 F FALSE 0.1751799 FALSE
## 381 0 3 M TRUE 0.3215447 FALSE
## 382 0 0 M TRUE 0.2757800 FALSE
table(high_use = alc$high_use, prediction = alc$prediction)
## prediction
## high_use FALSE TRUE
## FALSE 258 12
## TRUE 86 26
table(high_use = alc$high_use, prediction = alc$prediction) %>% prop.table %>% addmargins
## prediction
## high_use FALSE TRUE Sum
## FALSE 0.67539267 0.03141361 0.70680628
## TRUE 0.22513089 0.06806283 0.29319372
## Sum 0.90052356 0.09947644 1.00000000
loss_func <- function(class, prob) {
n_wrong <- abs(class - prob) > 0.5
mean(n_wrong)
}
loss_func(class = alc$high_use, prob = alc$probability)
## [1] 0.2565445
loss_func <- function(class, prob) {
n_wrong <- abs(class - prob) > 0.5
mean(n_wrong)}
loss_func(class = alc$high_use, prob = alc$probability)
## [1] 0.2565445
library(boot)
cv <- cv.glm(data = alc, cost = loss_func, glmfit = m, K = 10)
cv$delta[1]
## [1] 0.2591623
title: “Chapter4” output: html_document —
library(MASS)
##
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
##
## select
str(Boston)
## 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
dim(Boston)
## [1] 506 14
==================================================== # The Boston data consists of housing values in suburbs of Boston with data frame consisting of 506 rows and 14 columns containing variables. ========================================================
library(ggplot2)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
cor_matrix<-cor(Boston)
print(cor_matrix)
## crim zn indus chas nox
## crim 1.00000000 -0.20046922 0.40658341 -0.055891582 0.42097171
## zn -0.20046922 1.00000000 -0.53382819 -0.042696719 -0.51660371
## indus 0.40658341 -0.53382819 1.00000000 0.062938027 0.76365145
## chas -0.05589158 -0.04269672 0.06293803 1.000000000 0.09120281
## nox 0.42097171 -0.51660371 0.76365145 0.091202807 1.00000000
## rm -0.21924670 0.31199059 -0.39167585 0.091251225 -0.30218819
## age 0.35273425 -0.56953734 0.64477851 0.086517774 0.73147010
## dis -0.37967009 0.66440822 -0.70802699 -0.099175780 -0.76923011
## rad 0.62550515 -0.31194783 0.59512927 -0.007368241 0.61144056
## tax 0.58276431 -0.31456332 0.72076018 -0.035586518 0.66802320
## ptratio 0.28994558 -0.39167855 0.38324756 -0.121515174 0.18893268
## black -0.38506394 0.17552032 -0.35697654 0.048788485 -0.38005064
## lstat 0.45562148 -0.41299457 0.60379972 -0.053929298 0.59087892
## medv -0.38830461 0.36044534 -0.48372516 0.175260177 -0.42732077
## rm age dis rad tax
## crim -0.21924670 0.35273425 -0.37967009 0.625505145 0.58276431
## zn 0.31199059 -0.56953734 0.66440822 -0.311947826 -0.31456332
## indus -0.39167585 0.64477851 -0.70802699 0.595129275 0.72076018
## chas 0.09125123 0.08651777 -0.09917578 -0.007368241 -0.03558652
## nox -0.30218819 0.73147010 -0.76923011 0.611440563 0.66802320
## rm 1.00000000 -0.24026493 0.20524621 -0.209846668 -0.29204783
## age -0.24026493 1.00000000 -0.74788054 0.456022452 0.50645559
## dis 0.20524621 -0.74788054 1.00000000 -0.494587930 -0.53443158
## rad -0.20984667 0.45602245 -0.49458793 1.000000000 0.91022819
## tax -0.29204783 0.50645559 -0.53443158 0.910228189 1.00000000
## ptratio -0.35550149 0.26151501 -0.23247054 0.464741179 0.46085304
## black 0.12806864 -0.27353398 0.29151167 -0.444412816 -0.44180801
## lstat -0.61380827 0.60233853 -0.49699583 0.488676335 0.54399341
## medv 0.69535995 -0.37695457 0.24992873 -0.381626231 -0.46853593
## ptratio black lstat medv
## crim 0.2899456 -0.38506394 0.4556215 -0.3883046
## zn -0.3916785 0.17552032 -0.4129946 0.3604453
## indus 0.3832476 -0.35697654 0.6037997 -0.4837252
## chas -0.1215152 0.04878848 -0.0539293 0.1752602
## nox 0.1889327 -0.38005064 0.5908789 -0.4273208
## rm -0.3555015 0.12806864 -0.6138083 0.6953599
## age 0.2615150 -0.27353398 0.6023385 -0.3769546
## dis -0.2324705 0.29151167 -0.4969958 0.2499287
## rad 0.4647412 -0.44441282 0.4886763 -0.3816262
## tax 0.4608530 -0.44180801 0.5439934 -0.4685359
## ptratio 1.0000000 -0.17738330 0.3740443 -0.5077867
## black -0.1773833 1.00000000 -0.3660869 0.3334608
## lstat 0.3740443 -0.36608690 1.0000000 -0.7376627
## medv -0.5077867 0.33346082 -0.7376627 1.0000000
corrplot::corrplot(cor_matrix, method="circle", type="upper", cl.pos="b", tl.pos="d", tl.cex = 0.6)
====================== Crime rates are strongly correlated with index of accessibility to radial highways ======================
boston_scaled<-scale(Boston)
summary(boston_scaled)
## crim zn indus
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668
## Median :-0.390280 Median :-0.48724 Median :-0.2109
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202
## chas nox rm age
## Min. :-0.2723 Min. :-1.4644 Min. :-3.8764 Min. :-2.3331
## 1st Qu.:-0.2723 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366
## Median :-0.2723 Median :-0.1441 Median :-0.1084 Median : 0.3171
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.:-0.2723 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059
## Max. : 3.6648 Max. : 2.7296 Max. : 3.5515 Max. : 1.1164
## dis rad tax ptratio
## Min. :-1.2658 Min. :-0.9819 Min. :-1.3127 Min. :-2.7047
## 1st Qu.:-0.8049 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876
## Median :-0.2790 Median :-0.5225 Median :-0.4642 Median : 0.2746
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6617 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058
## Max. : 3.9566 Max. : 1.6596 Max. : 1.7964 Max. : 1.6372
## black lstat medv
## Min. :-3.9033 Min. :-1.5296 Min. :-1.9063
## 1st Qu.: 0.2049 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median : 0.3808 Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.4332 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 0.4406 Max. : 3.5453 Max. : 2.9865
class(boston_scaled)
## [1] "matrix"
boston_scaled<-as.data.frame(boston_scaled)
summary(boston_scaled$crim)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -0.419367 -0.410563 -0.390280 0.000000 0.007389 9.924110
bins<-quantile(boston_scaled$crim)
print(bins)
## 0% 25% 50% 75% 100%
## -0.419366929 -0.410563278 -0.390280295 0.007389247 9.924109610
crime<-cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, label<-c("low","med_low","med_high","high"))
table(crime)
## crime
## low med_low med_high high
## 127 126 126 127
boston_scaled <-dplyr::select(boston_scaled, -crim)
boston_scaled <-data.frame(boston_scaled, crime)
boston_scaled <-data.frame(boston_scaled, crime)
n<-nrow(boston_scaled)
ind<-sample(n,size = n*0.8)
train <- boston_scaled[ind,]
test <- boston_scaled[-ind,]
correct_classes<-(test$crime)
test <- dplyr::select(test, -crime)
lda.fit <- lda(crime~zn+indus+chas+nox+rm+age+dis+rad+tax+ptratio+black+lstat+medv, data = train)
lda.fit
## Call:
## lda(crime ~ zn + indus + chas + nox + rm + age + dis + rad +
## tax + ptratio + black + lstat + medv, data = train)
##
## Prior probabilities of groups:
## low med_low med_high high
## 0.2376238 0.2524752 0.2475248 0.2623762
##
## Group means:
## zn indus chas nox rm
## low 1.0346748 -0.9071307 -0.06727176 -0.8770586 0.4886655
## med_low -0.1622988 -0.2566486 -0.07933396 -0.5349620 -0.2086277
## med_high -0.3920529 0.1558552 0.20012296 0.3039838 0.1471721
## high -0.4872402 1.0149946 -0.01233188 1.0163877 -0.4660909
## age dis rad tax ptratio
## low -0.8613398 0.8261272 -0.6959508 -0.7265194 -0.51113308
## med_low -0.2578866 0.2898149 -0.5438774 -0.4535680 -0.01116012
## med_high 0.3857740 -0.3661253 -0.4007469 -0.3165306 -0.21918962
## high 0.8090949 -0.8408418 1.6596029 1.5294129 0.80577843
## black lstat medv
## low 0.3775179 -0.78287566 0.56805765
## med_low 0.3120506 -0.06356836 -0.05846496
## med_high 0.1085479 0.01001766 0.18116503
## high -0.6912887 0.85333661 -0.62404536
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## zn 0.09906438 0.8491229969 -0.847123357
## indus 0.07162857 -0.3373812205 0.151209206
## chas -0.09043894 -0.0098615178 -0.005695602
## nox 0.21829987 -0.7201968019 -1.387453141
## rm -0.13923866 -0.1159355368 -0.280106800
## age 0.26913012 -0.2532875389 -0.070845853
## dis -0.11100673 -0.3605273051 0.223888211
## rad 3.53788988 0.7872642409 -0.007994686
## tax -0.07018567 0.1774554167 0.604504370
## ptratio 0.08648343 0.0009896238 -0.191052018
## black -0.13650766 0.0174635125 0.145451285
## lstat 0.13410944 -0.3366754193 0.312415036
## medv 0.14500868 -0.4216340213 -0.138653901
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9539 0.0338 0.0123
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
classes<-as.numeric(train$crime)
plot(lda.fit, col=classes, dimen = 2)
lda.arrows(lda.fit, myscale = 1)
lda.pred <- predict(lda.fit, newdata = test)
table(correct = correct_classes, predicted = lda.pred$class)
## predicted
## correct low med_low med_high high
## low 19 10 2 0
## med_low 8 14 2 0
## med_high 0 9 16 1
## high 0 0 1 20
========================================= Classifier seem to predict the crime rates correctly =========================================
summary(Boston)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
class(Boston)
## [1] "data.frame"
dist_eu<-(Boston)
summary(dist_eu)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
set.seed(123)
k_max <- (10)
twcss <- sapply(1:k_max, function(k){kmeans(Boston, k)$tot.withinss})
km<-kmeans(Boston, centers = 2)
pairs(Boston[1:5], col = km$cluster)
=========================================================================================== Optimal number of clusters seems to be 2. Crime rates seems to be highly correlated with nox ===========================================================================================
km <- kmeans(Boston, centers = 3)
pairs(Boston[1:5], col = km$cluster)
# Scaling original Boston data
boston_scaled <- scale(Boston)
summary(boston_scaled)
## crim zn indus
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668
## Median :-0.390280 Median :-0.48724 Median :-0.2109
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202
## chas nox rm age
## Min. :-0.2723 Min. :-1.4644 Min. :-3.8764 Min. :-2.3331
## 1st Qu.:-0.2723 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366
## Median :-0.2723 Median :-0.1441 Median :-0.1084 Median : 0.3171
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.:-0.2723 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059
## Max. : 3.6648 Max. : 2.7296 Max. : 3.5515 Max. : 1.1164
## dis rad tax ptratio
## Min. :-1.2658 Min. :-0.9819 Min. :-1.3127 Min. :-2.7047
## 1st Qu.:-0.8049 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876
## Median :-0.2790 Median :-0.5225 Median :-0.4642 Median : 0.2746
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6617 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058
## Max. : 3.9566 Max. : 1.6596 Max. : 1.7964 Max. : 1.6372
## black lstat medv
## Min. :-3.9033 Min. :-1.5296 Min. :-1.9063
## 1st Qu.: 0.2049 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median : 0.3808 Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.4332 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 0.4406 Max. : 3.5453 Max. : 2.9865
class(boston_scaled)
## [1] "matrix"
boston_scaled<-as.data.frame(boston_scaled)
lda.fit <- lda(km$cluster~ ., data = boston_scaled)
lda.fit
## Call:
## lda(km$cluster ~ ., data = boston_scaled)
##
## Prior probabilities of groups:
## 1 2 3
## 0.5296443 0.1996047 0.2707510
##
## Group means:
## crim zn indus chas nox rm
## 1 -0.3920779 0.27670879 -0.6513071 0.0214843827 -0.6152775 0.2573427
## 2 -0.3293317 -0.07332724 0.2818828 0.0005392655 0.2816899 -0.1453417
## 3 1.0097765 -0.48724019 1.0662784 -0.0424254043 0.9959393 -0.3962652
## age dis rad tax ptratio black
## 1 -0.4572006 0.5121870 -0.6013344 -0.78136288 -0.2690134 0.34109296
## 2 0.1822823 -0.2378455 -0.5418150 -0.01444889 -0.3768823 0.07010933
## 3 0.7599946 -0.8265965 1.5757732 1.53915759 0.8040926 -0.71893398
## lstat medv
## 1 -0.43621538 0.36234147
## 2 0.01371321 -0.03812375
## 3 0.84321670 -0.68070813
##
## Coefficients of linear discriminants:
## LD1 LD2
## crim 0.048210477 0.05079118
## zn 0.253528315 0.06311589
## indus 0.369497254 0.12674727
## chas -0.047064817 0.01998369
## nox -0.063156250 -0.49621758
## rm -0.005144383 0.09537352
## age -0.118710969 0.05412142
## dis -0.385151599 0.17969944
## rad 1.996321584 3.05733525
## tax 4.535785039 -2.77688761
## ptratio 0.122064688 0.19196217
## black -0.029200518 0.06353722
## lstat 0.085030308 0.12666624
## medv 0.157444662 -0.10356584
##
## Proportion of trace:
## LD1 LD2
## 0.9812 0.0188
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
classes<-as.numeric(km$cluster)
plot(lda.fit, col=classes, dimen = 2)
lda.arrows(lda.fit, myscale = 1)
====================================================== tax and rad are the most influential linear separators for the clusters ======================================================
lda.fit <- lda(crime~zn+indus+chas+nox+rm+age+dis+rad+tax+ptratio+black+lstat+medv, data = train)
lda.fit
## Call:
## lda(crime ~ zn + indus + chas + nox + rm + age + dis + rad +
## tax + ptratio + black + lstat + medv, data = train)
##
## Prior probabilities of groups:
## low med_low med_high high
## 0.2376238 0.2524752 0.2475248 0.2623762
##
## Group means:
## zn indus chas nox rm
## low 1.0346748 -0.9071307 -0.06727176 -0.8770586 0.4886655
## med_low -0.1622988 -0.2566486 -0.07933396 -0.5349620 -0.2086277
## med_high -0.3920529 0.1558552 0.20012296 0.3039838 0.1471721
## high -0.4872402 1.0149946 -0.01233188 1.0163877 -0.4660909
## age dis rad tax ptratio
## low -0.8613398 0.8261272 -0.6959508 -0.7265194 -0.51113308
## med_low -0.2578866 0.2898149 -0.5438774 -0.4535680 -0.01116012
## med_high 0.3857740 -0.3661253 -0.4007469 -0.3165306 -0.21918962
## high 0.8090949 -0.8408418 1.6596029 1.5294129 0.80577843
## black lstat medv
## low 0.3775179 -0.78287566 0.56805765
## med_low 0.3120506 -0.06356836 -0.05846496
## med_high 0.1085479 0.01001766 0.18116503
## high -0.6912887 0.85333661 -0.62404536
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## zn 0.09906438 0.8491229969 -0.847123357
## indus 0.07162857 -0.3373812205 0.151209206
## chas -0.09043894 -0.0098615178 -0.005695602
## nox 0.21829987 -0.7201968019 -1.387453141
## rm -0.13923866 -0.1159355368 -0.280106800
## age 0.26913012 -0.2532875389 -0.070845853
## dis -0.11100673 -0.3605273051 0.223888211
## rad 3.53788988 0.7872642409 -0.007994686
## tax -0.07018567 0.1774554167 0.604504370
## ptratio 0.08648343 0.0009896238 -0.191052018
## black -0.13650766 0.0174635125 0.145451285
## lstat 0.13410944 -0.3366754193 0.312415036
## medv 0.14500868 -0.4216340213 -0.138653901
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9539 0.0338 0.0123
model_predictors <- dplyr::select(train, -crime, -crime.1)
dim(model_predictors)
## [1] 404 13
dim(lda.fit$scaling)
## [1] 13 3
dim(model_predictors)
## [1] 404 13
dim(lda.fit$scaling)
## [1] 13 3
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)
library(plotly)
##
## Attaching package: 'plotly'
## The following object is masked from 'package:MASS':
##
## select
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color=train$crime)
human2 <-read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/human2.txt",header = T, sep=",")
library(ggplot2)
library(GGally)
ggpairs(human2, lower = list(combo = wrap("facethist", bins = 20)))
========================================================================================= Correlations among 8 variables can be seen from the above ggpairs plot. It is noticeble that there exits a highest positive correlation between Life expectancy at birth and Expected years of schooling . Whereas, there exists a highest negative correlation between Maternal mortality ratio and Life expectancy at birth. =========================================================================================
summary(human2)
## Edu2.FM Labo.FM Edu.Exp Life.Exp
## Min. :0.1717 Min. :0.1857 Min. : 5.40 Min. :49.00
## 1st Qu.:0.7264 1st Qu.:0.5984 1st Qu.:11.25 1st Qu.:66.30
## Median :0.9375 Median :0.7535 Median :13.50 Median :74.20
## Mean :0.8529 Mean :0.7074 Mean :13.18 Mean :71.65
## 3rd Qu.:0.9968 3rd Qu.:0.8535 3rd Qu.:15.20 3rd Qu.:77.25
## Max. :1.4967 Max. :1.0380 Max. :20.20 Max. :83.50
## GNI Mat.Mor Ado.Birth Parli.F
## Min. : 581 Min. : 1.0 Min. : 0.60 Min. : 0.00
## 1st Qu.: 4198 1st Qu.: 11.5 1st Qu.: 12.65 1st Qu.:12.40
## Median : 12040 Median : 49.0 Median : 33.60 Median :19.30
## Mean : 17628 Mean : 149.1 Mean : 47.16 Mean :20.91
## 3rd Qu.: 24512 3rd Qu.: 190.0 3rd Qu.: 71.95 3rd Qu.:27.95
## Max. :123124 Max. :1100.0 Max. :204.80 Max. :57.50
library(ggfortify)
pca_human2 <- prcomp(human2)
summary(pca_human2)
## Importance of components:
## PC1 PC2 PC3 PC4 PC5 PC6 PC7
## Standard deviation 1.854e+04 185.5219 25.19 11.45 3.766 1.566 0.1912
## Proportion of Variance 9.999e-01 0.0001 0.00 0.00 0.000 0.000 0.0000
## Cumulative Proportion 9.999e-01 1.0000 1.00 1.00 1.000 1.000 1.0000
## PC8
## Standard deviation 0.1591
## Proportion of Variance 0.0000
## Cumulative Proportion 1.0000
================================================================================== We can obtain 8 principal components PC1-8. Each of these explains a percentage of the total variation in the dataset. That is to say: PC1 explains 99% of the total variance, which means that nearly all of the information in the dataset (8 variables) can be encapsulated by just that one Principal Component. PC2 explains 0.001 of the variance. So, by knowing the position of a sample in relation to just PC1 and PC2, we can get a very accurate view on where it stands in relation to other samples, as just PC1 and PC2 can explain 99% of the variance. ==================================================================================
pca_human2 <- prcomp(human2)
biplot(pca_human2, choices = 1:2, cex=c(0.8,1), col=c("grey40", "deeppink2"))
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length
## = arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length
## = arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length
## = arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length
## = arrow.len): zero-length arrow is of indeterminate angle and so skipped
## Warning in arrows(0, 0, y[, 1L] * 0.8, y[, 2L] * 0.8, col = col[2L], length
## = arrow.len): zero-length arrow is of indeterminate angle and so skipped
human_std <- scale(human2)
summary(human_std)
## Edu2.FM Labo.FM Edu.Exp Life.Exp
## Min. :-2.8189 Min. :-2.6247 Min. :-2.7378 Min. :-2.7188
## 1st Qu.:-0.5233 1st Qu.:-0.5484 1st Qu.:-0.6782 1st Qu.:-0.6425
## Median : 0.3503 Median : 0.2316 Median : 0.1140 Median : 0.3056
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.5958 3rd Qu.: 0.7350 3rd Qu.: 0.7126 3rd Qu.: 0.6717
## Max. : 2.6646 Max. : 1.6632 Max. : 2.4730 Max. : 1.4218
## GNI Mat.Mor Ado.Birth Parli.F
## Min. :-0.9193 Min. :-0.6992 Min. :-1.1325 Min. :-1.8203
## 1st Qu.:-0.7243 1st Qu.:-0.6496 1st Qu.:-0.8394 1st Qu.:-0.7409
## Median :-0.3013 Median :-0.4726 Median :-0.3298 Median :-0.1403
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.3712 3rd Qu.: 0.1932 3rd Qu.: 0.6030 3rd Qu.: 0.6127
## Max. : 5.6890 Max. : 4.4899 Max. : 3.8344 Max. : 3.1850
=================================================== By scaling the human data all the mean values for the varaibles were reduced to zero ===================================================
pca_human <- prcomp(human_std)
biplot(pca_human, choices = 1:2, cex=c(0.8,1), col=c("grey40", "deeppink2"))
s <- summary(pca_human)
s
## Importance of components:
## PC1 PC2 PC3 PC4 PC5 PC6
## Standard deviation 2.0708 1.1397 0.87505 0.77886 0.66196 0.53631
## Proportion of Variance 0.5361 0.1624 0.09571 0.07583 0.05477 0.03595
## Cumulative Proportion 0.5361 0.6984 0.79413 0.86996 0.92473 0.96069
## PC7 PC8
## Standard deviation 0.45900 0.32224
## Proportion of Variance 0.02634 0.01298
## Cumulative Proportion 0.98702 1.00000
pca_pr <- round(100*s$importance[2,], digits = 1)
pca_pr
## PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8
## 53.6 16.2 9.6 7.6 5.5 3.6 2.6 1.3
pc_lab <- paste0(names(pca_pr), " (", pca_pr, "%)")
biplot(pca_human, cex = c(0.8, 1), col = c("grey40", "deeppink2"), xlab = pc_lab[1], ylab = pc_lab[2])
===================================================================================================== Standardised data gives a better idea of the variability, with Maternal mortality ratio and Adolescent birth rate cvontributing to the PC1 which explains upto 53.6 variation. While, F/M ratio in the labour force and Percetange of female representatives in parliament contributing to PC2 which explains upto 16.2% variation. Additionally, Maternal mortality ratio and Adolescent birth rate seem to be strongly correlated, whereas F/M ratio in the labour force and Percetange of female representatives in parliament seem to correlate positively. =====================================================================================================
library(FactoMineR)
library(dplyr)
tea<-read.table("http://factominer.free.fr/factomethods/datasets/tea.txt",header = T, sep="\t")
str(tea)
## 'data.frame': 300 obs. of 36 variables:
## $ breakfast : Factor w/ 2 levels "breakfast","Not.breakfast": 1 1 2 2 1 2 1 2 1 1 ...
## $ tea.time : Factor w/ 2 levels "Not.tea time",..: 1 1 2 1 1 1 2 2 2 1 ...
## $ evening : Factor w/ 2 levels "evening","Not.evening": 2 2 1 2 1 2 2 1 2 1 ...
## $ lunch : Factor w/ 2 levels "lunch","Not.lunch": 2 2 2 2 2 2 2 2 2 2 ...
## $ dinner : Factor w/ 2 levels "dinner","Not.dinner": 2 2 1 1 2 1 2 2 2 2 ...
## $ always : Factor w/ 2 levels "always","Not.always": 2 2 2 2 1 2 2 2 2 2 ...
## $ home : Factor w/ 2 levels "home","Not.home": 1 1 1 1 1 1 1 1 1 1 ...
## $ work : Factor w/ 2 levels "Not.work","work": 1 1 2 1 1 1 1 1 1 1 ...
## $ tearoom : Factor w/ 2 levels "Not.tearoom",..: 1 1 1 1 1 1 1 1 1 2 ...
## $ friends : Factor w/ 2 levels "friends","Not.friends": 2 2 1 2 2 2 1 2 2 2 ...
## $ resto : Factor w/ 2 levels "Not.resto","resto": 1 1 2 1 1 1 1 1 1 1 ...
## $ pub : Factor w/ 2 levels "Not.pub","pub": 1 1 1 1 1 1 1 1 1 1 ...
## $ Tea : Factor w/ 3 levels "black","Earl Grey",..: 1 1 2 2 2 2 2 1 2 1 ...
## $ How : Factor w/ 4 levels "alone","lemon",..: 1 3 1 1 1 1 1 3 3 1 ...
## $ sugar : Factor w/ 2 levels "No.sugar","sugar": 2 1 1 2 1 1 1 1 1 1 ...
## $ how : Factor w/ 3 levels "tea bag","tea bag+unpackaged",..: 1 1 1 1 1 1 1 1 2 2 ...
## $ where : Factor w/ 3 levels "chain store",..: 1 1 1 1 1 1 1 1 2 2 ...
## $ price : Factor w/ 6 levels "p_branded","p_cheap",..: 4 6 6 6 6 3 6 6 5 5 ...
## $ age : int 39 45 47 23 48 21 37 36 40 37 ...
## $ sex : Factor w/ 2 levels "F","M": 2 1 1 2 2 2 2 1 2 2 ...
## $ SPC : Factor w/ 7 levels "employee","middle",..: 2 2 4 6 1 6 5 2 5 5 ...
## $ Sport : Factor w/ 2 levels "Not.sportsman",..: 2 2 2 1 2 2 2 2 2 1 ...
## $ age_Q : Factor w/ 5 levels "+60","15-24",..: 4 5 5 2 5 2 4 4 4 4 ...
## $ frequency : Factor w/ 4 levels "+2/day","1 to 2/week",..: 3 3 1 3 1 3 4 2 1 1 ...
## $ escape.exoticism: Factor w/ 2 levels "escape-exoticism",..: 2 1 2 1 1 2 2 2 2 2 ...
## $ spirituality : Factor w/ 2 levels "Not.spirituality",..: 1 1 1 2 2 1 1 1 1 1 ...
## $ healthy : Factor w/ 2 levels "healthy","Not.healthy": 1 1 1 1 2 1 1 1 2 1 ...
## $ diuretic : Factor w/ 2 levels "diuretic","Not.diuretic": 2 1 1 2 1 2 2 2 2 1 ...
## $ friendliness : Factor w/ 2 levels "friendliness",..: 2 2 1 2 1 2 2 1 2 1 ...
## $ iron.absorption : Factor w/ 2 levels "iron absorption",..: 2 2 2 2 2 2 2 2 2 2 ...
## $ feminine : Factor w/ 2 levels "feminine","Not.feminine": 2 2 2 2 2 2 2 1 2 2 ...
## $ sophisticated : Factor w/ 2 levels "Not.sophisticated",..: 1 1 1 2 1 1 1 2 2 1 ...
## $ slimming : Factor w/ 2 levels "No.slimming",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ exciting : Factor w/ 2 levels "exciting","No.exciting": 2 1 2 2 2 2 2 2 2 2 ...
## $ relaxing : Factor w/ 2 levels "No.relaxing",..: 1 1 2 2 2 2 2 2 2 2 ...
## $ effect.on.health: Factor w/ 2 levels "effect on health",..: 2 2 2 2 2 2 2 2 2 2 ...
dim(tea)
## [1] 300 36
glimpse(tea)
## Observations: 300
## Variables: 36
## $ breakfast <fct> breakfast, breakfast, Not.breakfast, Not.brea...
## $ tea.time <fct> Not.tea time, Not.tea time, tea time, Not.tea...
## $ evening <fct> Not.evening, Not.evening, evening, Not.evenin...
## $ lunch <fct> Not.lunch, Not.lunch, Not.lunch, Not.lunch, N...
## $ dinner <fct> Not.dinner, Not.dinner, dinner, dinner, Not.d...
## $ always <fct> Not.always, Not.always, Not.always, Not.alway...
## $ home <fct> home, home, home, home, home, home, home, hom...
## $ work <fct> Not.work, Not.work, work, Not.work, Not.work,...
## $ tearoom <fct> Not.tearoom, Not.tearoom, Not.tearoom, Not.te...
## $ friends <fct> Not.friends, Not.friends, friends, Not.friend...
## $ resto <fct> Not.resto, Not.resto, resto, Not.resto, Not.r...
## $ pub <fct> Not.pub, Not.pub, Not.pub, Not.pub, Not.pub, ...
## $ Tea <fct> black, black, Earl Grey, Earl Grey, Earl Grey...
## $ How <fct> alone, milk, alone, alone, alone, alone, alon...
## $ sugar <fct> sugar, No.sugar, No.sugar, sugar, No.sugar, N...
## $ how <fct> tea bag, tea bag, tea bag, tea bag, tea bag, ...
## $ where <fct> chain store, chain store, chain store, chain ...
## $ price <fct> p_unknown, p_variable, p_variable, p_variable...
## $ age <int> 39, 45, 47, 23, 48, 21, 37, 36, 40, 37, 32, 3...
## $ sex <fct> M, F, F, M, M, M, M, F, M, M, M, M, M, M, M, ...
## $ SPC <fct> middle, middle, other worker, student, employ...
## $ Sport <fct> sportsman, sportsman, sportsman, Not.sportsma...
## $ age_Q <fct> 35-44, 45-59, 45-59, 15-24, 45-59, 15-24, 35-...
## $ frequency <fct> 1/day, 1/day, +2/day, 1/day, +2/day, 1/day, 3...
## $ escape.exoticism <fct> Not.escape-exoticism, escape-exoticism, Not.e...
## $ spirituality <fct> Not.spirituality, Not.spirituality, Not.spiri...
## $ healthy <fct> healthy, healthy, healthy, healthy, Not.healt...
## $ diuretic <fct> Not.diuretic, diuretic, diuretic, Not.diureti...
## $ friendliness <fct> Not.friendliness, Not.friendliness, friendlin...
## $ iron.absorption <fct> Not.iron absorption, Not.iron absorption, Not...
## $ feminine <fct> Not.feminine, Not.feminine, Not.feminine, Not...
## $ sophisticated <fct> Not.sophisticated, Not.sophisticated, Not.sop...
## $ slimming <fct> No.slimming, No.slimming, No.slimming, No.sli...
## $ exciting <fct> No.exciting, exciting, No.exciting, No.exciti...
## $ relaxing <fct> No.relaxing, No.relaxing, relaxing, relaxing,...
## $ effect.on.health <fct> No.effect on health, No.effect on health, No....
================================================================================================================================================== Tea dataset contains 300 observations (8)tea consumers) of 36 variables of answeres to a survey about their consumption of tea. These include how they consume tea, how they think of tea and descriptive questions (sex, age, socio-professional category and sport practise). Except for the age, all the variables are categorical. For the age, the data set has two different variables: a continuous and a categorical one ==================================================================================================================================================
res.mca = MCA(tea, quanti.sup=19, quali.sup=c(20:36))
plot.MCA(res.mca, invisible=c("var","quali.sup"), cex=0.7)
plot.MCA(res.mca, invisible=c("ind","quali.sup"), cex=0.7)
plot.MCA(res.mca, invisible=c("ind"))
plot.MCA(res.mca, invisible=c("ind", "var"))
=============================================================================================================================================== We can see on the individuals’ scatterplot that there is no particular group of individuals. The scatterplot is quite homogeneous.
To interpret the principal components of the MCA, we are going to use extreme individuals (it is easier than using directly groups of individuals). Individuals 265 and 273 like and often drink tea in any occasion. Individuals 200 and 262 only drink tea at home, at breakfast or in the evening.
There are too many individuals to look at each one by one. That is why we need a representation of the categories
Variables “price”, “where” and “how” are much linked to both first and second dimensions. We cannot say much more and need a representation of categories to interpret these relationships better.
The first dimension opposes “tea room”, “chain store+tea shop”, “tea bag+unpackaged”, “pub”, “resto”, “work” between “not friends”, “not resto”, “not work”, “not home”. It opposes regular tea drinkers to occasional ones.
The second dimension opposes “specialized shop”, “unpackaged” and “upscale price” to other categories.
The variable “age” is not well represented. However, its correlation with the second dimension is significant (0.204) since we have a lot of individuals. Young people tend to buy tea in other places than specialized shops when old people tend to buy expensive unpackaged tea in specialized shops.
It is quite difficult to say anything about categorical supplementary variables since their categories are located at the center of the graph. However, it is possible to hide active categories and look at supplementary ones only. We then see that the categories of the variable “age_Q” are ordered from “15-24” to “+60” along the second dimension. This is in relation with the positive coordinate of the variable “age” on the second dimension.
================================================================================================================================================
plotellipses(res.mca,keepvar=c(20:23))
library("factoextra")
## Welcome! Related Books: `Practical Guide To Cluster Analysis in R` at https://goo.gl/13EFCZ
eig.val <- get_eigenvalue(res.mca)
head(eig.val)
## eigenvalue variance.percent cumulative.variance.percent
## Dim.1 0.14827441 9.884961 9.884961
## Dim.2 0.12154673 8.103115 17.988076
## Dim.3 0.09000954 6.000636 23.988712
## Dim.4 0.07805440 5.203627 29.192339
## Dim.5 0.07374870 4.916580 34.108919
## Dim.6 0.07138044 4.758696 38.867615
fviz_screeplot(res.mca, addlabels = TRUE, ylim = c(0, 45))